package com.kvn.btrace.tool;

import java.util.List;

import com.google.common.collect.Lists;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

/**
* @author wzy
* @date 2017年10月12日 下午7:46:11
*/
public class BTraceUtil {
	private static final String BTRACE_HOME = "D:\btrace-bin-1.3.9";
	
	public static void startBTrace(String targetVM, String btraceScriptPath){
		System.setProperty("com.sun.btrace.probeDescPath", ".");
		System.setProperty("com.sun.btrace.dumpClasses", "false");
		System.setProperty("com.sun.btrace.debug", "false"); // debug 开关
		System.setProperty("com.sun.btrace.unsafe", "false");
		com.sun.btrace.client.Main main = new com.sun.btrace.client.Main();
		List<String> bArgs = Lists.newArrayList();
		bArgs.add("-cp");
		bArgs.add(BTRACE_HOME + "/build/btrace-client.jar;%JAVA_HOME%/lib/tools.jar");
		
		List<VirtualMachineDescriptor> vms = VirtualMachine.list();
		for (VirtualMachineDescriptor vmd: vms) {
		    if (vmd.displayName().equals(targetVM)) {
		    	bArgs.add(vmd.id()); // pid
		    }
		}
		bArgs.add(btraceScriptPath);
		
		main.main(bArgs.toArray(new String[]{}));
	}

}
